﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZFY.AspNetCore
{
    public class ZFYResultFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.ModelState.IsValid)
            {
                

                if (context.Result is ObjectResult result)
                {
                    var statusCode = result.StatusCode ?? context.HttpContext.Response.StatusCode;
                    if (statusCode == StatusCodes.Status200OK && result.Value.GetType().Name != typeof(ZFYReponse<>).Name)
                    {
                        var res = new ZFYReponse<object>()
                        {
                            Data = result.Value,
                            Success = true,
                            Msg = "操作成功"
                        };

                        result.Value = res;
                        result.DeclaredType = res.GetType();

                        
                    }
                }
            }
            else
            {
                var list = new List<string>();
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        list.Add(error.ErrorMessage);
                    }
                }

                var res = new ZFYReponse<List<string>>()
                {
                    Data = list,
                    Success = false
                };

                context.Result = new ObjectResult(res)
                {
                    //ContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { "application/json" },
                    StatusCode = StatusCodes.Status400BadRequest,
                    DeclaredType = res.GetType()
                };
            }
            await next();
        }
    }
}
